<template>
    <rx-dialog @ok="handleSubmit" @cancel="cancel">
        <div class="report">
            <div>
                <a-form  ref="form" layout="vertical" :model="dataMode" :rules="rules">
                    <a-form-item :label="i18n('form.modelName','模型名称')" prop="name">
                        <a-input :placeholder="i18n('form.modelName','模型名称')" v-model:value="dataMode.name"/>
                    </a-form-item>
                    <a-form-item :label="i18n('form.classify','分类')" prop="categoryId">
                        <rx-category-select cat-key="SCREEN" :isGrant="true" v-model="dataMode.categoryId" :appId="appId"></rx-category-select>
                    </a-form-item>
                    <a-form-item  :label="i18n('form.thirdPartyInterface','第三方接口')" prop="dataSource">
                        <rx-input-button v-model="dataMode.dataSource" style="width: 100%;" class="input-button-edit" @btnClick="getInterface" :singleValue="false">
                            <template #addonAfter>
                                <rx-icon-show icon="icon-lineVue3_search" ></rx-icon-show>
                            </template>
                        </rx-input-button>
                    </a-form-item>
                    <a-form-item  :label="i18n('form.ResultKey','结果集Key')">
                        <a-input :placeholder="i18n('form.ResultKey','结果集Key')" v-model:value="resultKey"/>
                    </a-form-item>
                </a-form>
            </div>
            <div>
                <div class="tables_obj" style="margin-top: 15px">
                    <span style="flex: 1">{{i18n('form.modelSet','数据模型设置')}}</span>
                </div>
                <div class="model">
                    <div class="model_chart"><span style="flex: 1">{{i18n('form.dimension','维度')}}</span>
                        <a style="margin-right: 10px" @click="unhideAll('dimension')">{{i18n('form.unHideAll','全部取消隐藏')}}</a></div>
                    <div class="model_chart"><span style="flex: 1">{{i18n('form.measure','度量')}} </span>
                        <a style="margin-right: 10px" @click="unhideAll('measure')">{{i18n('form.unHideAll','全部取消隐藏')}}</a></div><div>{{i18n('form.param','参数')}}</div>
                </div>
                <div class="model_content modeboder">
                    <div >
                        <a-collapse  :bordered="false" default-active-key="1"  v-for="(dimension,index) in dimensions" :key="index">
                            <template #expandIcon="props">
                                <caret-right-outlined :rotate="props.isActive ? 90 : 0"/>
                            </template>
                            <a-collapse-panel key="1" :header="i18n('form.dimension','维度')">
                                <div style="margin-top: -10px">
                                    <div class="model_obj" v-for="(field,index1) in dimension.fields" :key="field.fieldName">
                                        <rx-icon-show @mouseenter="mouseenter(index,index1,'dimension')"
                                                      :icon="getIcon(field)" :class="field.hide?'model_decoration':''"
                                                      style="color:#02c5b7;margin-right: 6px"></rx-icon-show>
                                        <span style="font-size: 12px;" :class="{'model_decoration':field.hide}"
                                              @mouseenter="mouseenter(index,index1,'dimension')">{{ field.fieldLabel }}</span>
                                        <a-dropdown :trigger="['click']" v-show="parentid==index && childrenid==index1">
                                            <rx-icon-show icon="icon-linezhuanhuan" class="icon_ringht"></rx-icon-show>
                                            <template #overlay>
                                                <a-menu :selectedKeys="selectedKeys(field.dataFormat)" class="fonz12" v-show="parentid==index && childrenid==index1">
                                                    <a-menu-item key="switchTo">
                                                        <span @click="switchTo(index,index1,'measure')" class="fonz12">{{i18n('form.switchMetric','切换为度量')}}</span>
                                                    </a-menu-item>
                                                    <a-sub-menu v-if="field.dataType=='date'" class="fonz12"
                                                                key="dataFormat"
                                                                :title="i18n('form.dataFormat','数据格式')"
                                                    >
                                                        <a-menu-item class="fonz12" :key="item.value" v-for="item in dateFormatList"
                                                                     @click="setDataFormat(item.value,index,index1)">
                                                            {{item.label}}
                                                        </a-menu-item>
                                                    </a-sub-menu>
                                                    <a-menu-item key="hideField">
                                                        <span v-if="field.hide" @click="hideField(index,index1,'dimension',false)" class="fonz12">{{i18n('form.unhide','取消隐藏')}}</span>
                                                        <span v-else @click="hideField(index,index1,'dimension',true)" class="fonz12">{{i18n('form.hideField','隐藏字段')}}</span>
                                                    </a-menu-item>
                                                </a-menu>
                                            </template>
                                        </a-dropdown>
                                    </div>
                                </div>
                            </a-collapse-panel>
                        </a-collapse>
                    </div>
                    <div >
                        <a-collapse  :bordered="false" default-active-key="1"  v-for="(measure,index) in measures" :key="index">
                            <template #expandIcon="props">
                                <caret-right-outlined :rotate="props.isActive ? 90 : 0"/>
                            </template>
                            <a-collapse-panel key="1" :header="i18n('form.measure','度量')">
                                <div style="margin-top: -10px">
                                    <div class="model_obj" v-for="(field,index1) in measure.fields" :key="field.fieldName">
                                        <rx-icon-show @mouseenter="mouseenter(index,index1,'measure')"
                                                      :icon="getIcon(field)" :class="field.hide?'model_decoration':''"
                                                      style="color:#02c5b7;margin-right: 6px"></rx-icon-show>
                                        <span style="font-size: 12px;" :class="{'model_decoration':field.hide}" @mouseenter="mouseenter(index,index1,'measure')">{{ field.fieldLabel }}</span>
                                        <a-dropdown :trigger="['click']" v-show="MRparentid==index && MRchildrenid==index1">
                                            <rx-icon-show icon="icon-linezhuanhuan" class="icon_ringht"></rx-icon-show>
                                            <template #overlay>
                                                <a-menu :selectedKeys="selectedKeys(field.aggregate)" class="fonz12" v-show="MRparentid==index && MRchildrenid==index1">
                                                    <a-menu-item key="switchTo">
                                                        <span @click="switchTo(index,index1,'dimension')" class="fonz12">{{i18n('form.toDimension','切换为维度')}}</span>
                                                    </a-menu-item>
                                                    <a-sub-menu key="aggregate" class="fonz12"
                                                                :title="i18n('form.polymerize','聚合') + '('+field.aggregate+')'">
                                                        <a-menu-item :key="item.value" class="fonz12" v-for="item in aggregates"
                                                                     @click="setAggregate(item.value,index,index1)">
                                                            {{item.label}}
                                                        </a-menu-item>
                                                    </a-sub-menu>
                                                    <a-menu-item key="hideField">
                                                        <span v-if="field.hide" @click="hideField(index,index1,'measure',false)" class="fonz12">{{i18n('form.unhide','取消隐藏')}}</span>
                                                        <span v-else @click="hideField(index,index1,'measure',true)" class="fonz12">{{i18n('form.hideField','隐藏字段')}}</span>
                                                    </a-menu-item>
                                                </a-menu>
                                            </template>
                                        </a-dropdown>
                                    </div>
                                </div>
                            </a-collapse-panel>
                        </a-collapse>
                    </div>
                    <div>
                        <a-collapse  :bordered="false" default-active-key="1"  v-for="(param,index) in params" :key="index">
                            <template #expandIcon="props">
                                <caret-right-outlined :rotate="props.isActive ? 90 : 0"/>
                            </template>
                            <a-collapse-panel key="1" :header="i18n('form.param','参数')">
                                <div style="margin-top: -10px">
                                    <div class="model_obj" v-for="(field,index1) in param.fields" :key="field.fieldName">
                                        <rx-icon-show @mouseenter="mouseenter(index,index1,'param')"
                                                      :icon="getIcon(field)"
                                                      style="color:#02c5b7;margin-right: 6px"></rx-icon-show>
                                        <span style="font-size: 12px;" @mouseenter="mouseenter(index,index1,'param')">{{ field.fieldLabel }}</span>
                                    </div>
                                </div>
                            </a-collapse-panel>
                        </a-collapse>
                    </div>
                </div>
            </div>
        </div>
    </rx-dialog>
</template>

<script>
import {RxDialog, RxInputButton, Util} from '@lowcode/jpaas-base-lib';
import { ShareDialog,RxCategorySelect } from '@lowcode/jpaas-share-component';
import designJs from "./js/design-js";
import ScreenDataModelApi from '@/api/screen/core/screen-data-model';
import useMain from "../../../../stores/use-main";
import {mapState} from 'pinia';
export default {
    name: "InterfaceDesign",
    mixins:[designJs],
    components: {
        RxDialog,
        RxInputButton,
        RxCategorySelect
    },
    computed: {
        ...mapState(useMain, ['appId'])
    },
    props: {
        pkId:{
            type:String,
            default: ""
        }
    },
    data() {
        return {
            dataMode:{
                name:"",
                categoryId:"",
                sourceType:"interface",
                modelConfig:"",
            },
            rules: {
                name: [{required: true, message: this.i18n('form.modelName','模型名称'), trigger: 'change'}],
                categoryId: [{required: true, message: this.i18n('form.classify','分类'), trigger: 'blur'}]
            },
            //接口 返回字段
            returnFields:[],
            resultKey:"",
            labelCol: {span: 6},
            wrapperCol: {span: 18},
        }
    },
    created() {
        if(this.pkId){
            this.getById();
        }
    },
    methods: {
        getById() {
            ScreenDataModelApi.get(this.pkId).then(res=>{
                if(res && res.data){
                    this.dataMode=Object.assign(this.dataMode,res.data);
                    if(this.dataMode.modelConfig){
                        let modelConfig=JSON.parse(this.dataMode.modelConfig);
                        this.dimensions=modelConfig.dimensions;
                        this.measures=modelConfig.measures;
                        this.params=modelConfig.params;
                    }
                    if(this.dataMode.dataSource){
                        let dataSource=JSON.parse(this.dataMode.dataSource);
                        this.resultKey=dataSource.resultKey||""
                    }
                }
            });
        },
        save() {
            let modelConfig = {
                "dimensions": this.dimensions,
                "measures": this.measures,
                "params":this.params
            }
            this.dataMode.modelConfig =JSON.stringify(modelConfig);
            if(this.dataMode.dataSource){
                let dataSource=JSON.parse(this.dataMode.dataSource);
                dataSource.resultKey=this.resultKey||"";
                this.dataMode.dataSource=JSON.stringify(dataSource);
            }
            let appId = this.appId;
            if(appId){
                this.dataMode.appId=appId;
            }
            ScreenDataModelApi.save(this.dataMode).then(() => {
                Util.closeWindow(this, 'ok');
            });
        },
        getInterface(){
            let self=this;
            ShareDialog.openSysInterfaceDialog({
                curVm: this,max:true,
            }, function ( data) {
                let jsonObj = {label:data.apiName, value:data.apiKey};
                self.dataMode.dataSource = JSON.stringify(jsonObj);
                self.dimensions=[];
                self.measures=[];
                self.params=[];
                //参数
                let param=self.getParams(data.apiBody,data.apiQuery,data.apiHeaders,data.apiDataType);
                self.params.push(param);
                //返回字段
                if(data.apiReturnFields && data.apiReturnFields!='[]'){
                    self.returnFields=self.getReturnField(JSON.parse(data.apiReturnFields));
                }else {
                    self.returnFields=[];
                }
                self.initFields();
            })
        },
        //获取返回字段
        getReturnField(data){
            let returnFields=[];
            if(!data){
                return returnFields;
            }
            for (let i = 0; i < data.length; i++) {
                if(data[i].isChild){
                    returnFields=data[i].children;
                    break;
                }else if(data[i].children){
                    returnFields=this.getReturnField(data[i].children);
                }
            }
            return returnFields;
        },
        //初始化字段
        initFields(){
            let dimensions=[];
            let measures=[];
            for (let i = 0; i < this.returnFields.length; i++) {
                let data=this.returnFields[i];
                let dataType = data.paramType;
                let obj = {
                    dataType: dataType,
                    fieldLabel: data.paramDesc || data.paramName,
                    fieldName: data.paramName
                };
                if (dataType == 'string') {
                    obj.icon = 'icon-lineField-String';
                } else if (dataType == 'date') {
                    obj.icon =  'icon-lineriqi2';
                } else if (dataType == 'number') {
                    obj.icon = 'icon-lineshuzi';
                }
                //度量
                if (dataType == "number") {
                    obj["aggregate"] = "SUM";
                    measures.push(obj);
                }
                //维度
                else {
                    //默认日期格式
                    if (obj.dataType == 'date') {
                        obj["dataFormat"] = "YYYY-MM-DD";
                    }
                    dimensions.push(obj);
                }
            }
            let dimension={
                tableName:"",
                fields:dimensions
            }
            let measure={
                tableName:"",
                fields:measures
            }
            this.dimensions.push(dimension);
            this.measures.push(measure);
        },
        //图标
        getIcon(obj) {
            if (obj.dataType == 'string') {
                return 'icon-lineField-String';
            } else if (obj.dataType == 'date') {
                return 'icon-lineriqi2';
            } else  {
                return 'icon-lineshuzi';
            }
        },
        //构建参数
        getParams(body,query,header,dataType){
            let params=[];
            let bodys=[];
            let querys=[];
            let headers=[];
            if(body && body!='[]'){
                bodys=JSON.parse(body);
                if(dataType=='json'){
                    for (let i = 0; i < bodys.length; i++) {
                        if(bodys[i].isRoot){
                            let bodyFields=this.getFields(bodys[i].children);
                            params.push(...bodyFields);
                        }
                    }
                }
            }
            if(query && query!='[]'){
                querys=JSON.parse(query);
                params.push(...this.getFields(querys));
            }
            if(header && header!='[]'){
                headers=JSON.parse(header);
                params.push(...this.getFields(headers));
            }
            return {
                tableName:"",
                fields:params
            };
        },
        getFields(data,parentName){
            let fields=[];
            if(!data){
                return fields;
            }
            for (let i = 0; i < data.length; i++) {
                //获取传入参数
                if(data[i].paramSource && data[i].paramSource=="param"){
                    let fieldName=parentName?parentName+"."+data[i].paramName : data[i].paramName;
                    let obj = {
                        dataType: data[i].paramType || "string",
                        fieldLabel: data[i].paramDesc || fieldName,
                        fieldName: fieldName
                    };
                    fields.push(obj);
                }else if(data[i].paramType=="object" && data[i].children && data[i].children.length>0){//对象
                    let childernFields=this.getFields(data[i].children,data[i].paramName);
                    fields.push(...childernFields);
                }
            }
            return fields;
        },
        handleSubmit() {
            this.save();
        },
        cancel() {
            Util.closeWindow(this, 'cancel');
        },
    },
    watch: {},
}
</script>

<style scoped>

.report{
    display: flex;
    width: 100%;
    height: 100%;
}
.report >div:nth-child(1){
    width: 380px;
    height: 100%;
    overflow: auto;
    padding: 15px;
    border-right: 1px solid #e6e8eb;
}
.report >div:nth-child(2){
    flex: 1;
    padding: 15px 15px 0px 15px;
    overflow: auto;
}
.tables_obj{
    color: #46494d;
    border-left: 2px solid #1890ff;
    line-height: 10px;
    padding-left: 8px;
    display: flex;

}
.model_chart{
    display: flex;
}
.model_obj{
    margin:0px 0px 10px 20px;
    cursor:pointer;
    position: relative;
}
.model_content{
    display: flex;
    width: 100%;
    height: calc(100% - 296px);
    border-radius: 10px;
}
.model_content >div{
    flex: 1;
    padding-top: 10px;
    height: 100%;
    overflow: auto;
}
.model_content >div:nth-child(1){
    border-right: 1px solid #dadde0;
}
.model_content >div:nth-child(2){
    border-right: 1px solid #dadde0;
}
.model_content .ant-collapse-content > .ant-collapse-content-box{
    padding: 10px 5px 0px 18px!important;
}
.model_content .ant-collapse > .ant-collapse-item > .ant-collapse-header{
    padding:4px 16px 4px 40px!important;
}
.model_content .ant-collapse-header{
    height: 30px!important;
}
.model_content .ant-collapse-borderless{
    background: white!important;
}

.model {
    display: flex;
    width: 100%;
    line-height: 30px;
    color: #808080;
    background-color: #f5f7fa;
    border: solid 1px #dadde0;
    margin-top: 6px;
    font-size: 12px;
}

.model > div:nth-child(1) {
    border-right: solid 1px #dadde0;
}

.model > div {
    flex: 1;
    padding-left: 15px;
}

</style>
